package collector

import (
	"database/sql"
	"log/slog"

	"github.com/prometheus/client_golang/prometheus"
)

const (
	// Scrape query.
	// select 'rows', sum(table_rowcount(owner,table_name)) from dba_tables where owner not in ('SYS','SYSDBA','SYSAUDITOR','SYSSSO') union all
	statiticsQuery = `select 'users' k,count(1)v  from dba_users union all 
	select 'tables' , count(1) from dba_tables union all
	select 'running_time',unix_timestamp(now())-unix_timestamp(start_time) from v$instance union all
	select 'license_expired_time', CASE WHEN expired_date IS NULL THEN -1 ELSE unix_timestamp(expired_date) END from v$license union all
	select 'arch_mode',case when arch_mode = 'n' then 0 else 1 end from v$database union all
	select 'page_size',page
	`

	// Subsystem.
	statisticsInfo = "statistics_info"
)

var (
	statisticsInfoDesc = prometheus.NewDesc(
		prometheus.BuildFQName(namespace, statisticsInfo, "count_data"),
		"The DM overview info statistics data.",
		[]string{"items"}, nil,
	)
)

type StatisticsInfo struct {
}

func (StatisticsInfo) Name() string {
	return "statisticsInfo"
}
func (StatisticsInfo) Scrape(db *sql.DB, ch chan<- prometheus.Metric, backupPath string, logger *slog.Logger) error {

	var (
		itmes string
		val   float64
	)
	staticsInfoRows, err := db.Query(statiticsQuery)
	if err != nil {
		logger.Error("Failed to query statistics info", "error", err)
		return err
	}
	defer staticsInfoRows.Close()
	for staticsInfoRows.Next() {
		if err := staticsInfoRows.Scan(&itmes, &val); err != nil {
			logger.Error("Failed to scan statistics info row", "error", err)
			return err
		}
		ch <- prometheus.MustNewConstMetric(
			statisticsInfoDesc, prometheus.GaugeValue, val,
			itmes,
		)

	}

	return nil
}

func init() {
	RegisterScraper("statisticsInfo", StatisticsInfo{})
}

var _ Scraper = StatisticsInfo{}
